<?php

namespace DataCube\DataCubeAggregation\Utils;

use DateTimeImmutable;

class DateTime
{
    public function __call($name, $arguments)
    {
        if (strpos($name, 'groupTimestampsBy') === 0 || $name == 'groupBy') {
            $className = __NAMESPACE__ . "\\DateTime\\GroupByFunc";
            if ($name === 'groupBy') {
                return $this->groupBy($name, $arguments[0]);
            }
            if (class_exists($className) && method_exists($className, $name)) {
                return call_user_func_array(array(new $className(), $name), [$arguments[0]]);
            }
        }
    }

    public static function __callStatic($name, $arguments)
    {
        if (strpos($name, 'groupTimestampsBy') === 0 || $name == 'groupBy') {
            $className = __NAMESPACE__ . "\\DateTime\\GroupByFunc";
            if (class_exists($className) && method_exists($className, $name)) {
                return call_user_func_array(array(new $className(), $name), [$arguments[0]]);
            }
        }
        $className = __NAMESPACE__ . "\\DateTime\\DateTimeUtils";
        if (class_exists($className) && method_exists($className, $name)) {
            return call_user_func_array(array(new $className(), $name), [$arguments[0]]);
        }
    }

    public function groupBy($method, array $timestamps)
    {
        $className = __NAMESPACE__ . "\\DateTime\\GroupByFunc";
        if (class_exists($className) && method_exists($className, $method)) {
            return call_user_func_array(array(new $className(), $method), [$timestamps]);
        }
    }

    /**
     * Round minutes to the nearest interval of a DateTime object.
     *
     * @param DateTimeImmutable $dateTime
     * @param int $minuteInterval
     * @return DateTimeImmutable
     */
    public function roundToNearestMinuteInterval(DateTimeImmutable $dateTime, int $minuteInterval = 10): DateTimeImmutable
    {
        return $dateTime->setTime(
            (int)$dateTime->format('H'),
            (int)round($dateTime->format('i') / $minuteInterval) * $minuteInterval,
            0
        );
    }
}
